<?php
# The document handler
# $_GET["id"]		->		document id
# $_GET["method"]	->		"v": view
#							"e": edit
#							"c": create

require_once("user_session.php");
if(isset($_GET["method"])){
	$method = $_GET["method"];
} else {
	$method = "v";
}
if(isset($_GET["id"])){
	$id = $_GET["id"];
} else {
	$id = "_0";
}

$_SESSION["position"] = "document.php?id=".$id."&method=".$method; 

Switch ($method){
	case "v":
		if(EKDocument::testExist($_GET["id"])){
			viewPerspective();
		} else {
			if(isset($_GET["id"])){
				echo "No document with Id:" . $_GET["id"]. ".";
			} else {
				echo "No dId specified!";
			}
		}
		break;
	case "c":
		//User can't direct type this link in the browser
		createPerspective();
		break;
	case "e":
		break;
	echo "<script language=javascript>\n".
				        "alert(\" Illegal request! \");\n".
				        "history.go(-1);\n".
				        "</script>";
}
	

function authorityTable($template,$type,$id,$status,$uid){# authorityTable() is to handle the displayed options of a EKAElement.
# $template is the phplib template handler.
# $type is current EKAElement type.
#		"pr" = EKAParagraphRelationship.
#		"p" = EKAParagraph.
#		"d" = EKADocument.
# $id is current EKAElement Id.
# $status is current EKAElement status.
# $uid is current EKAElement creater/author id.

# EKAElement is a super class of:
# 		EKADocument
#		EKAParagraphRelationship
#		EKAParagraph
#		EKATalk
#		EKARating
#		EKAEvents
	
	if(!isset($_SESSION['userid'])||$_SESSION['userid']==""){
	#############
	# For guest #
	#############
		if($type=="pr"){
			$template->set_var("pr_options","Login to edit!");
		} else if ($type=="p"){
			$template->set_var("p_options","Login to talk!");
		} else if ($type=="d"){
			$template->set_var("options","Login to talk!");
		}
	} else if($_SESSION['userid'] == $uid){
	######################
	# For creator/author #
	######################
		if ($type=="p"){
			if($status=="pending" && EKParagraph::getOwnerIdById($id)!="_0"){
				$template->set_var("p_options","
					<a href=\"talk_create.php?ownerId=".$id."&talkType=p\">[+ Talk]</a>
					<a href=\"paragraph.php?id=". $id ."\">[@ Modify]</a> 
					<a onclick=\"adminAndDel('paragraph_delete.php?id=". $id ."')\">[-- Delete]</a>"
				);
			} else {
				$template->set_var("p_options","
					<a href=\"talk_create.php?ownerId=".$id."&talkType=p\">[+ Talk]</a>
					<a href=\"paragraph.php?id=". $id ."\">[@ Modify]</a>"
				);
			}
		} else if($type=="pr"){
			if($status=="pending"){
				$template->set_var("pr_options","pending");
			}else{
				$template->set_var("pr_options","You've added subvision");
			}
		} else if($type=="d"){
			if($status=="pending"){
				$template->set_var("options","
				<a onclick=\"adminAndDel('document_delete.php?id=".$id."')\">[-- Delete]</a> 
				<a href=\"talk_create.php?ownerId=".$id."&talkType=d\">[+ Talk]</a>");
			}else{
				$template->set_var("options"," 
				<a href=\"document.php?id=".$id."&method=c\">[++ Child]</a> 
				<a href=\"talk_create.php?ownerId=".$id."&talkType=d\">[+ Talk]</a>");
			}
		} else if ($type == "p_t"){
			$template->set_var("p_t_options","");
		} else if ($type == "t"){
			$template->set_var("t_options","");
		}
	} else if($_SESSION['userType'] != "0"){
	##########################################
	# For committee/arbitrator/administrator #
	##########################################
		if($type=="pr"){
			If($status=="pending"){
				$template->set_var("pr_options","pending");
			} else {
				$template->set_var("pr_options",
					"
					<a href=\"paragraph.php?id=". $id ."\">[+ Edit]</a>
					"
				);				
			}	
		} else if ($type=="p"){
			if ($status=="pending"){
				$template->set_var("p_options",
					"
					<a href=\"talk_create.php?ownerId=".$id."&talkType=p\">[+ Talk]</a>
					 
					<a onclick=\"adminAndDel('administrate.php?eventType=approve&elementType=p&id=".$id."')\">[# Approve]</a> 
					<a onclick=\"adminAndDel('administrate.php?eventType=deny&elementType=p&id=".$id."')\">[# Deny]</a> 
					"
				);
			} else {
				$template->set_var("p_options",
					"
					<a href=\"talk_create.php?ownerId=".$id."&talkType=p\">[+ Talk]</a>
					"
					#."
					#<a href=\"administrate.php?eventType=disapprove&elementType=p&id=".$id."\">[# Disapprove]</a> 
					#"
				);
			}
		} else if ($type=="d"){
			if ($status=="pending"){
				$template->set_var("options",
					"
					<a href=\"talk_create.php?ownerId=".$id."&talkType=d\">[+ Talk]</a> 
					<a onclick=\"adminAndDel('administrate.php?eventType=approve&elementType=d&id=".$id."')\">[# Approve]</a> 
					<a onclick=\"adminAndDel('administrate.php?eventType=deny&elementType=d&id=".$id."')\">[# Deny]</a> 
					"
				);
			} else {
				$template->set_var("options",
					"
					<a href=\"talk_create.php?ownerId=".$id."&talkType=d\">[+ Talk]</a> 
					<a href=\"document.php?id=".$id."&method=c\">[++ Child]</a>"
					#."
					#<a href=\"administrate.php?eventType=disapprove&elementType=d&id=".$id."\">[# Disapprove]</a>
					#"
				);
			}
		} else if ($type == "p_t"){
			$template->set_var("p_t_options",
				"<a onclick=\"adminAndDel('administrate.php?eventType=deny&elementType=t&id=".$id."')\">[-- Delete]</a>");
		} else if ($type == "t"){
			$template->set_var("t_options",
				"<a onclick=\"adminAndDel('administrate.php?eventType=deny&elementType=t&id=".$id."')\">[-- Delete]</a>");
		}
	} else {
	############
	# For user #
	############
		if($type=="pr"){
			If($status=="pending"){
				$template->set_var("pr_options","");
			} else {
				$template->set_var("pr_options",
					"
					<a href=\"paragraph.php?id=". $id ."\">[+ Edit]</a>
					"
				);				
			}	
		} else if ($type=="p"){
			$template->set_var("p_options","<a href=\"talk_create.php?ownerId=".$id."&talkType=p\">[+ Talk]</a>");
		} else if ($type=="d"){
			if ($status=="pending"){
				$template->set_var("options","
					<a href=\"talk_create.php?ownerId=".$id."&talkType=d\">[+ Talk]</a> 
					");
			} else {
				$template->set_var("options","<a href=\"talk_create.php?ownerId=".$id."&talkType=d\">[+ Talk]</a> 
					<a href=\"document.php?id=".$id."&method=c\">[++ Child]</a>");
			}
		}
	}
}

function viewPerspective(){
	
	if(isset($_GET["id"])){
		$id = $_GET["id"];
	} else {
		$id = "_0";
	}
	# Construct a new document instance by $id
	$currentDoc = new EKDocument($id);
	
	# Generate template outputs
	if($currentDoc->ifEnabled()){
		
		$template = new Template();
		$template->set_file("document","template/document.html");
		
		$template->set_file("footer","template/footer.html");
		$template->parse("footer","footer");
		
		setTemplateWithSession($template);
		getEvents($template);
		
		# Set page title
		$template->set_var("pageTitle","[". $currentDoc->getTitle() . "] :: " . SITENAME);
		
		# Set Current Time
		$template->set_var("currentTime",time());
		
		# Set document title
		$template->set_var("title",$currentDoc->getTitle());
		$template->set_var("d_id",$id);
		
		# Set document status
		$template->set_var("status",$currentDoc->getStatus());
		
		# Set creator name
		$template->set_var("creator",EKUser::getAttributeById($currentDoc->getCreatorId(),"name"));
		$template->set_var("creator_link","user.php?userid=".$currentDoc->getCreatorId()."&method=v");
		
		# Set updateTime
		$template->set_var("update_time",$currentDoc->getUpdateTime());
		
		# Set the ratings
		# ratingType string<=>int convertion
		# d = 1
		# p = 2
		# t = 3
		
		if ($currentDoc->getFatherId() == "null"){
			$template->set_var("rating_display_class","rating_null");
			$template->set_var("rating_class","rating");
		} else if(!isset($_SESSION['userid'])||$_SESSION['userid']==""){
			$template->set_var("rating_class","rating_static");
		} else {
			$template->set_var("rating_class","rating");
		}
		
		$template->set_var("rating_a_id","rating_11".substr($id,1));
		$template->set_var("rating_b_id","rating_12".substr($id,1));
		$template->set_var("rating_a_value",$currentDoc->getRatingAValue());
		$template->set_var("rating_b_value",$currentDoc->getRatingBValue());
		$template->set_var("ip",$_SERVER['REMOTE_ADDR']);
		
		# Set displayed paragraphs
		# Most Complex Part!
		$paragraphIdArray = $currentDoc->getParagraphIdArray();
		
		$template->set_block("document","pr_list","pRList");
		$template->set_block("pr_list","p_list","pList");
		$template->set_block("p_list","p_ref_list","pRefList");
		$template->set_block("p_list","p_internal_link_list","pInternalLinkList");
		$template->set_block("p_list","p_talk_list","pTalkList");
		
		# Display all the paragraph relationships
		for($i=0;$i<count($paragraphIdArray);$i++){
			
			$tempPRIds = $currentDoc->getPRIds();
			$template->set_var("pr_update_time", EKParagraphRelationship::getUpdateTimeById($tempPRIds[$i]));
			
			# Options for paragraph relationship
			$paragraphRelationshipAuthors = Array();
			foreach($paragraphIdArray[$i] as $paragraphId){
				$paragraphRelationshipAuthors[] = EKElement::getElementValueById($paragraphId, "EKParagraph", "authorId");
			}
			if(in_array($_SESSION['userid'],$paragraphRelationshipAuthors)){
				authorityTable($template,"pr",$paragraphIdArray[$i][0],$currentDoc->getStatus(),$_SESSION['userid']);
			} else {
				authorityTable($template,"pr",$paragraphIdArray[$i][0],$currentDoc->getStatus(),"");
			}
			
			# Display parallel paragraphs
			$template->set_var("pList");
			
			for($j=0;$j<count($paragraphIdArray[$i]);$j++){
				$paragraphArray[$i][$j] = new EKParagraph($paragraphIdArray[$i][$j]);
				
				# Update the Internal Link inside one paragraph
				EKParagraph::upadteInternalLinkById($paragraphIdArray[$i][$j]);
				
				if($paragraphArray[$i][$j]->getStatus()=="approved"){
					$template->set_var("p_style_class","p_a");
					$template->set_var("p_header_style_class","p_header_a");
					$template->set_var("p_close_style_class","p_close_a");
					$template->set_var("p_style_modifier","display:block");
				} else if($j == 0){
					$template->set_var("p_style_class","p_p");
					$template->set_var("p_header_style_class","p_header_p");
					$template->set_var("p_close_style_class","p_close_p");
					$template->set_var("p_style_modifier","display:block");
				} else {
					$template->set_var("p_style_class","p_p");
					$template->set_var("p_header_style_class","p_header_p");
					$template->set_var("p_close_style_class","p_close_p");
					$template->set_var("p_style_modifier","display:none");
				}
				$template->set_var("p_id",$paragraphIdArray[$i][$j]);
				$template->set_var("p_update_time",$paragraphArray[$i][$j]->getUpdateTime());
				
				$template->set_var("p_rating_a_id","rating_21".substr($paragraphIdArray[$i][$j],1));
				$template->set_var("p_rating_b_id","rating_22".substr($paragraphIdArray[$i][$j],1));
				$template->set_var("p_rating_a_value",$paragraphArray[$i][$j]->getRatingAValue());
				$template->set_var("p_rating_b_value",$paragraphArray[$i][$j]->getRatingBValue());
				
				$paragraphContent = str_replace("\n","<br />", $paragraphArray[$i][$j]->getContent());
				
				$template->set_var("p_content",$paragraphContent);
				$template->set_var("p_author_link","user.php?userid=".$paragraphArray[$i][$j]->getAutherId()."&method=v");
				$template->set_var("p_author",EKUser::getAttributeById($paragraphArray[$i][$j]->getAutherId(),"name"));
				
				
				# refs
				$template->set_var("p_ref_id","p_ref".$paragraphIdArray[$i][$j]);
				$template->set_var("pRefList");
				$refList = $paragraphArray[$i][$j]->getRefs();
				if(count($refList)!=0){
					foreach($refList as $ref)
					{
						$template->set_var("p_ref",$ref);
						$template->parse("pRefList","p_ref_list",true);
					}
				}
				
				# internalLinks 
				$template->set_var("p_internal_link_id","p_internal_link".$paragraphIdArray[$i][$j]);
				$template->set_var("pInternalLinkList");
				$pInternalLinkIdList = $paragraphArray[$i][$j]->getInternalLinkIds();
				if(count($pInternalLinkIdList)!=0){
					foreach($pInternalLinkIdList as $pInternalLinkId)
					{
						$template->set_var("p_internal_link_title",EKDocument::getTitleById($pInternalLinkId));
						$template->set_var("p_internal_link_url","document.php?id=".$pInternalLinkId."&method=v");
						$template->parse("pInternalLinkList","p_internal_link_list",true);
					}
				}
				
				# talks 
				$template->set_var("p_talk_id","p_talk".$paragraphIdArray[$i][$j]);
				$template->set_var("pTalkList");
				$pTalkIdList = $paragraphArray[$i][$j]->getTalkIds();
				
				if(count($pTalkIdList)!=0){
					foreach($pTalkIdList as $pTalkId)
					{
						$template->set_var("p_talk_content",EKTalk::getContentById($pTalkId));
						$talkAuthorId = EKElement::getElementValueById($pTalkId, "EKTalk", "authorId");
						$template->set_var("p_talk_author",EKUser::getAttributeById($talkAuthorId,"name"));
						$template->set_var("p_talk_author_link","user.php?userid=".$talkAuthorId."&method=v");
						$template->set_var("p_talk_time",EKTalk::getUpdateTimeById($pTalkId));
						
						$template->set_var("p_talk_rating_a_id","rating_31".substr($pTalkId,1));
						$template->set_var("p_talk_rating_b_id","rating_32".substr($pTalkId,1));
						$template->set_var("p_talk_rating_a_value",EKTalk::getRatingAValue($pTalkId));
						$template->set_var("p_talk_rating_b_value",EKTalk::getRatingBValue($pTalkId));
						authorityTable($template,"p_t",$pTalkId,"",$talkAuthorId);
						$template->parse("pTalkList","p_talk_list",true);
					}
				}
				
				# Set Options for paragraph
				authorityTable($template,"p",$paragraphIdArray[$i][$j],$paragraphArray[$i][$j]->getStatus(),$paragraphArray[$i][$j]->getAutherId());
				
				# Get Talk template
				# $template->parse("p_talk","talk");# 1st p_talk->variable in template, 2nd talk->template file
				
				$template->parse("pList","p_list",true);	
			}
			# End Inter loop
			
			$template->parse("pRList","pr_list",true);
		}
		# End Outer loop
		
		
		# Set ref_list
		#$template->set_block("document","ref_list","refList");
		
		#$refList = $currentDoc->getRefs();
		#if(count($refList)!=0){
		#	foreach($refList as $ref)
		#	{
		#		$template->set_var("ref",$ref);
		#		$template->parse("refList","ref_list",true);
		#	}
		#}
		
		# Set internal_link_list
		#$template->set_block("document","internal_link_list","internalLinkList");
		
		#$internalLinkIdList = $currentDoc->getInternalLinks();
		#if(count($internalLinkIdList)!=0){
		#	foreach($internalLinkIdList as $internalLinkId)
		#	{
		#		$template->set_var("internal_link_title",EKDocument::getTitleById($internalLinkId));
		#		$template->set_var("internal_link_url","document.php?id=".$internalLinkId."&method=v");
		#		$template->parse("internalLinkList","internal_link_list",true);
		#	}
		#}
		
		# Set talk_list
		$template->set_block("document","talk_list","talkList");
		
		$talkIdList = $currentDoc->getTalkIds();
		if(count($talkIdList)!=0){
			foreach($talkIdList as $talkId)
			{
				$template->set_var("talk_content",EKTalk::getContentById($talkId));
				$template->set_var("talk_author",EKUser::getAttributeById(EKElement::getElementValueById($talkId, "EKTalk", "authorId"),"name"));
				$template->set_var("talk_author_link","user.php?userid=".EKElement::getElementValueById($talkId, "EKTalk", "authorId")."&method=v");
				$template->set_var("talk_time",EKTalk::getUpdateTimeById($talkId));
				
				authorityTable($template,"t",$talkId,"","");
				$template->set_var("talk_rating_a_id","rating_31".substr($talkId,1));
				$template->set_var("talk_rating_b_id","rating_32".substr($talkId,1));
				$template->set_var("talk_rating_a_value",EKTalk::getRatingAValue($talkId));
				$template->set_var("talk_rating_b_value",EKTalk::getRatingBValue($talkId));
				
				$template->parse("talkList","talk_list",true);
			}
		}
		
		
		# Set childTitle/childLink
		$template->set_block("document","child_list","childList");
		$childIdList = $currentDoc->getChildIds();
		if(count($childIdList) == 0){
			$template->set_var("child_title","NO CHILD");
			$template->set_var("child_url","#");
			$template->parse("childList","child_list",true);
		} else {
			foreach($childIdList as $childId){
				$template->set_var("child_title",EKDocument::getTitleById($childId));
				$template->set_var("child_url","document.php?id=".$childId."&method=v");
				$template->parse("childList","child_list",true);
			}
		}
		
		
		# Set fatherTitle/fatherLink
		if($currentDoc->getFatherId() != "null"){
			$template->set_var("father_title",EKDocument::getTitleById($currentDoc->getFatherId()));
			$template->set_var("father_url","document.php?id=".$currentDoc->getFatherId()."&method=v");
		} else {
			$template->set_var("father_title","CURRENT NODE IS ROOT");
			$template->set_var("father_url","#");
		}
		
		# Set Options for document
		authorityTable($template,"d",$id,$currentDoc->getStatus(),$currentDoc->getCreatorId());
		
		# Parse & generate the output
		$template->parse("output","document");
		$template->p("output");
		
	} else {
		echo "Wrong document request...<br />";
	}
}

function createPerspective(){
	$parentId = $_GET["id"];
	if(!isset($_SESSION['userid'])||$_SESSION['userid']==""){
		# exception: not logged in!
		echo "<script language=javascript>\n".
				"alert(\"Please login!\");\n".
				"history.go(-1);\n".
				"</script>";
	} else {
		if($parentId == "null"){
			$template = new Template();
			$template->set_file("document_create","template/document_create.html");
			setTemplateWithSession($template);
			
			$fatherTitle = "CURRENT NODE IS ROOT";
			
			$template->set_var("pageTitle", "[++ SET ROOT] :: " . SITENAME);
			
			$template->set_var("title","Click to set title");
			$template->set_var("creator",$_SESSION['username']);
			$template->set_var("update_time",date("Y/m/d [H:i:s]",time()));
			
			$template->set_var("father_title",$fatherTitle);
			$template->set_var("father_url","#");
			$template->set_var("father_id","null");
			
			$template->parse("output","document_create");
			$template->p("output");
		} else {
			$template = new Template();
			$template->set_file("document_create","template/document_create.html");
			setTemplateWithSession($template);
			
			$fatherTitle = EKDocument::getTitleById($parentId);
			
			$template->set_var("pageTitle", "[++ Child] @ [". $fatherTitle . "] :: " . SITENAME);
			
			$template->set_var("title","Click to set title");
			$template->set_var("creator",$_SESSION['username']);
			$template->set_var("update_time",date("Y/m/d [H:i:s]",time()));
			
			$template->set_var("father_title",$fatherTitle);
			$template->set_var("father_url","document.php?id=".$parentId."&method=v");
			$template->set_var("father_id",$parentId);
			
			$template->parse("output","document_create");
			$template->p("output");
		}
	}
}
?>